#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <linux/rtc.h>
#include <time.h>
#include <fcntl.h>

#include "Rtc.h"

#include "sysdebug.h"
#include "sysarch.h"
#include "ComAPI.h"

#define  RX8025_RD_TIME     0x00007E00  //���fm24cl arm��С
#define  RX8025_SET_TIME    0x00007E01  //����fm24cl arm��С

bool RtcGetTime(TTime& time)
{
    struct tm tm;
    int rtc = open("/dev/at91_rx8025", O_RDONLY);

    if (rtc < 0)
    {
        Debug(DEBUG_CRITICAL, ("cannot open RTC\r\n"));
        return false;
    }

    memset(&tm, 0, sizeof(struct tm));
    if (ioctl(rtc, RX8025_RD_TIME, &tm) < 0)
    {
        Debug(DEBUG_CRITICAL, ("cannot read time from RTC\r\n"));
    }
    tm.tm_isdst = -1; /* not known */

    close(rtc);

    time.nSecond = tm.tm_sec;
    time.nMinute = tm.tm_min;
    time.nHour = tm.tm_hour;
    time.nDay = tm.tm_mday;
    time.nMonth = tm.tm_mon + 1; //RTCʱ���·ݴ�0��ʼ
    time.nYear = 1900 + tm.tm_year;
    time.nWeek = tm.tm_wday;

    return true;
}

bool RtcSetTime(const TTime& time)
{
    struct tm rtc;

    for (WORD i = 0; i < 3; i++)
    {
        int fd = open("/dev/at91_rx8025", O_RDWR);

        if (fd < 0)
        {
            return false;
        }

        rtc.tm_sec = time.nSecond;
        rtc.tm_min = time.nMinute;
        rtc.tm_hour = time.nHour;
        rtc.tm_mday = time.nDay;
        rtc.tm_mon = time.nMonth - 1;
        rtc.tm_year = (time.nYear - 1900);
        rtc.tm_wday = 1;

        ioctl(fd, RX8025_SET_TIME, &rtc);

        close(fd);

        Sleep(10);

        TTime tmRead;
        RtcGetTime(tmRead);
        DWORD dwWrSec = TimeToSeconds(time);
        DWORD dwRdSec = TimeToSeconds(tmRead);
        if (dwRdSec >= dwWrSec && dwRdSec - dwWrSec < 10)
        {
            return true;
        }
        else
        {
            Debug(DEBUG_CRITICAL, ("RtcSetTime : ~~~~~$$$$$$$$$$ write time to rtc err, write time %d-%02d-%02d %02d:%02d:%02d, read time %d-%02d-%02d %02d:%02d:%02d\r\n",
                                time.nYear, time.nMonth, time.nDay, time.nHour, time.nMinute, time.nSecond,
                                tmRead.nYear, tmRead.nMonth, tmRead.nDay, tmRead.nHour, tmRead.nMinute, tmRead.nSecond));
        }

        Sleep(10);
    }

    return false;
}


